#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initUI();
    initSignalSlot();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initUI()
{
    currentFileLabel = new QLabel;
    currentFileLabel->setMinimumWidth(150);
    currentFileLabel->setText("当前文件:");
    ui->statusbar->addWidget(currentFileLabel);

    progressBar = new QProgressBar;
    progressBar->setMaximumWidth(200);
    progressBar->setMinimum(5);
    progressBar->setMaximum(50);
    progressBar->setValue(ui->textEdit->font().pointSize());
    ui->statusbar->addWidget(progressBar);

    spinFontSize = new QSpinBox;
    spinFontSize->setMinimum(5);
    spinFontSize->setMaximum(50);
    spinFontSize->setValue(ui->textEdit->font().pointSize());
    spinFontSize->setMinimumWidth(50);

    comboFont = new QFontComboBox;
    comboFont->setMinimumWidth(150);

    ui->toolBar->addWidget(new QLabel("字体大小 "));
    ui->toolBar->addWidget(spinFontSize);
    ui->toolBar->addSeparator();
    ui->toolBar->addWidget(new QLabel(" 字体 "));
    ui->toolBar->addWidget(comboFont);

    setCentralWidget(ui->textEdit);
}

void MainWindow::initSignalSlot()
{
    connect(spinFontSize, SIGNAL(valueChanged(int)), this, SLOT(onSpinFontSize(int)));
    connect(comboFont, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(onComboFont(const QString&)));
}


void MainWindow::onSpinFontSize(int fontSize)
{
    QTextCharFormat charFormat;
    charFormat.setFontPointSize(fontSize);
    ui->textEdit->mergeCurrentCharFormat(charFormat);
    progressBar->setValue(fontSize);
}

void MainWindow::onComboFont(const QString &font)
{
    QTextCharFormat charFormat;
    charFormat.setFontFamily(font);
    ui->textEdit->mergeCurrentCharFormat(charFormat);
}

void MainWindow::on_actFontItalic_triggered(bool checked)
{
    QTextCharFormat charFormat = ui->textEdit->currentCharFormat();
    if (checked)
        charFormat.setFontWeight(QFont::Bold);
    else
        charFormat.setFontWeight(QFont::Normal);
    ui->textEdit->mergeCurrentCharFormat(charFormat);
}

void MainWindow::on_textEdit_copyAvailable(bool b)
{
    ui->actCut->setEnabled(b);
    ui->actCopy->setEnabled(b);
    ui->actpaste->setEnabled(ui->textEdit->canPaste());
}

void MainWindow::on_textEdit_selectionChanged()
{
    QTextCharFormat charFormat = ui->textEdit->currentCharFormat();
    ui->actFontItalic->setEnabled(charFormat.fontItalic());
    ui->actFontBold->setEnabled(charFormat.font().bold());
    ui->actFontUnder->setEnabled(charFormat.fontUnderline());
}
